const express = require('express')
const mongoose = require('mongoose')

//链接mongo 并且使用imooc这个集合
const DB_URL = 'mongodb://localhost:27017'
mongoose.connect(DB_URL)
mongoose.connection.on('connected',function () {
    console.log('mongo connect success')
})
//类似于mysql的表 mongo里有文档、字段的概念
const User =  mongoose.model('user',new mongoose.Schema({
    user:{type:String,require:true},
    age:{type:Number,require:true}
}))
//新增数据
User.create({
    user:'imooc',
    age:19
},function (err,doc) {
    if(!err) {
        console.log(doc)
    }else{
        console.log(err)
    }
})
//mongo 更新
User.update({'user':'imooc'},{'$set':{age:26}},function (err,doc) {
   console.log(doc)
})
//mongo 删除
User.remove({age:19},function(err,doc){
    console.log(doc)
})
//新建app
const app = express();
//监听根目录路由
app.get('/', function (req, res) {
//    返回一个html标签
    res.send('<h1>hello worls</h1>')
})
//mongo 查找
app.get('/data', function (req, res) {
    User.find({},function(err,doc){
        res.json(doc)
    })
    // res.json({name: 'imooc pskeeter', type: 'IT'})
})
//启动app
app.listen(9093, function () {
    console.log('Node app is running on port:9093')
})